<template>
	<view class="page-container">
		<view class="top">
			<view class="item">
				<view class="left">收货人</view>
				<input type="text" placeholder-class="line" placeholder="请填写收货人姓名" v-model="addressInfo.name" />
			</view>
			<view class="item">
				<view class="left">手机号码</view>
				<input type="text" placeholder-class="line" placeholder="请填写收货人手机号" v-model="addressInfo.tel" />
			</view>
			<view class="item" @click="showAreaPicker">
				<view class="left">所在地区</view>
				<input v-model="addressArea" disabled type="text" placeholder-class="line" placeholder="省-市-区县" />
			</view>
			<view class="item">
				<view class="left">详细地址</view>
				<input v-model="addressInfo.addressDetail" type="text" placeholder-class="line" placeholder="街道乡村门号" />
			</view>
			<view class="item">
				<view class="left">邮政编码</view>
				<input v-model="addressInfo.postalCode" type="number" maxlength="6" placeholder-class="line" placeholder="邮政编码" />
			</view>
		</view>
		<view class="bottom">
			
				<view class="left">
					<view class="set">设置默认地址</view>
					<view class="tips">提醒：每次下单会默认推荐该地址</view>
				</view>
				<view class="right"><u-switch v-model="addressInfo.isDefault"></u-switch></view>
			
		</view>
		<u-button type="primary" @click="onSave">保存</u-button>
		<br />
		<u-button type="error" v-if="!!id" @click="onDelete">删除</u-button>

		<u-picker
			ref="uPicker"
			class="uPicker"
			:show="showPicker"
			:columns="areaColumns"
			:defaultIndex="defaultIndex"
			@confirm="onConfirm"
			@cancel="showPicker = false"
			@change="changeHandler"
		/>
	</view>
</template>

<script>
import * as AddressAPI from '@/api/address.js';
import areaData from './areaFromVant.js';

export default {
	data() {
		return {
			areaList: [],  //{id,label,pid,level}
			defaultIndex: [0,0,0],
			areaColumns: [],			
			showPicker: false,
			id: '', //Address.id
			addressInfo: {
				//收货人信息初始值
				id: '', //每条地址的唯一标识
				name: '', //姓名
				tel: '', //电话
				province: '', //省份
				city: '', //城市
				county: '', //区县
				areaCode: '', //地区编码，通过省市区选择获取（必填）
				postalCode: '', //邮政编码
				addressDetail: '', //详细地址
				isDefault: false //是否选择默认
			}
		};
	},
	computed: {
		addressArea() {
			if (this.addressInfo.province) {
				if (this.addressInfo.province === this.addressInfo.city) return this.addressInfo.city + this.addressInfo.county;
				else return this.addressInfo.province + this.addressInfo.city + this.addressInfo.county;
			}
		}
	},
	// 生命周期方法
	onLoad(options) {
		this.initAreaList(); // 按要求结构构建数据
		this.id = options.id || null;
		console.log("onLoad : this.id ",this.id)
		if (this.id) {
			// 编辑地址
			this.getAddressDetail();
		} else {
			// 新增地址
			this.initColumnsData(); //初始 u-picker 组件参数
		}
	},
	methods: {
		// 按要求结构构建数据，Vant的地区数据的编号是有父子规律的
		initAreaList() {
			this.areaList = [];
			// 省数据
			Object.entries(areaData.province_list).forEach(item => {
				//item是一个只有2个元素的数组
				this.areaList.push({
					id: item[0],
					label: item[1],
					pid: 0,
					level: 1
				});
			});
			// 市数据
			Object.entries(areaData.city_list).forEach(item => {
				//item是一个只有2个元素的数组
				let pid = item[0].substring(0, 2) + '0000';
				this.areaList.push({
					id: item[0],
					label: item[1],
					pid: pid,
					level: 2
				});
			});
			// 县区数据
			Object.entries(areaData.county_list).forEach(item => {
				//item是一个只有2个元素的数组
				let pid = item[0].substring(0, 4) + '00';
				this.areaList.push({
					id: item[0],
					label: item[1],
					pid: pid,
					level: 3
				});
			});
		},

		//从后端获取地址数据
		getAddressDetail() {
			AddressAPI.getAddressDetailById(this.id).then(result => {
				this.addressInfo.id = result.data.id;
				this.addressInfo.name = result.data.name;
				this.addressInfo.tel = result.data.tel;
				this.addressInfo.province = result.data.province;
				this.addressInfo.city = result.data.city;
				this.addressInfo.county = result.data.county;
				this.addressInfo.areaCode = result.data.area_code; //
				this.addressInfo.postalCode = result.data.post_code; //
				this.addressInfo.addressDetail = result.data.address_detail; //
				this.addressInfo.isDefault = result.data.is_default == 1 ? true : false; //
				// 地区回填
				this.setAreaByCode(this.addressInfo.areaCode);
			});
		},

		//初始 u-picker 组件参数
		initColumnsData() {
			const indexProvice = 0; //初始索引
			const indexCity = 0; //初始索引
			const indexCounty = 0; //初始索引
			// 初始值
			// 省
			let tempList = this.areaList.filter(item => item.pid == 0);
			const columnsProvince = tempList.map(item => item.label);
			const codeProvince = tempList[indexProvice].id; //省份代码
			// 市
			tempList = this.areaList.filter(item => item.pid == codeProvince);
			const columnsCity = tempList.map(item => item.label);
			const codeCity = tempList[indexCity].id; //城市代码
			// 区县
			tempList = this.areaList.filter(item => item.pid == codeCity);
			const columnsCounty = tempList.map(item => item.label);

			this.areaColumns = [columnsProvince, columnsCity, columnsCounty];
			this.defaultIndex = [indexProvice, indexCity, indexCounty];
		},

		// 地区回填
		setAreaByCode(areaCode) {
			const codeCounty = areaCode + '';
			const codeCity = codeCounty.substring(0, 4) + '00'; //城市代码
			const codeProvince = codeCounty.substring(0, 2) + '0000'; //省份代码
			// 省
			let tempList = this.areaList.filter(item => item.pid == 0);
			let columnsProvince = tempList.map(item => item.label);
			let indexProvice = tempList.findIndex(item => item.id == codeProvince);
			indexProvice = indexProvice < 0 ? 0 : indexProvice;
			// 市
			tempList = this.areaList.filter(item => item.pid == codeProvince);
			let columnsCity = tempList.map(item => item.label);
			let indexCity = tempList.findIndex(item => item.id == codeCity);
			indexCity = indexCity < 0 ? 0 : indexCity;
			// 区县
			tempList = this.areaList.filter(item => item.pid == codeCity);
			let columnsCounty = tempList.map(item => item.label);
			let indexCounty = tempList.findIndex(item => item.id == codeCounty);
			indexCounty = indexCounty < 0 ? 0 : indexCounty;

			this.areaColumns = [columnsProvince, columnsCity, columnsCounty];
			this.defaultIndex = [indexProvice, indexCity, indexCounty];
			console.log(indexProvice, indexCity, indexCounty);
		},

		changeHandler(e) {
			const {
				columnIndex,
				value,
				values, // values为当前变化列的数组内容
				index,
				indexs,
				// 微信小程序无法将picker实例传出来，只能通过ref操作
				picker = this.$refs.uPicker
			} = e;
			//console.log(e);

			const nameProvince = value[0];
			const nameCity = value[1];
			let province = this.areaList.find(item => item.pid == 0 && item.label == nameProvince);
			if (!province) return;

			// 当第一列值发生变化时，变化第二列(后一列)对应的选项
			if (columnIndex === 0) {
				// picker为选择器this实例，变化第二列对应的选项
				let columnsCity = []; // 第2列城市选项
				columnsCity = this.areaList.filter(item => item.pid == province.id).map(item => item.label);
				picker.setColumnValues(1, columnsCity);

				let city = this.areaList.find(item => item.pid == province.id && item.label == nameCity);
				if (!city) return;

				let columnsCounty = []; // 第3列县区选项
				columnsCounty = this.areaList.filter(item => item.pid == city.id).map(item => item.label);
				picker.setColumnValues(2, columnsCounty);
			}
			// 当第二列值发生变化时
			if (columnIndex === 1) {
				let city = this.areaList.find(item => item.pid == province.id && item.label == nameCity);
				if (!city) return;

				let columnsCounty = []; // 第3列县区选项
				columnsCounty = this.areaList.filter(item => item.pid == city.id).map(item => item.label);
				picker.setColumnValues(2, columnsCounty);
			}			
		},
		
		// 确认选择地区值
		onConfirm(e) {
			this.showPicker = false;
			//console.log(e);
			let { value } = e;

			const nameProvince = value[0];
			const nameCity = value[1];
			const nameCounty = value[2];

			this.addressInfo.province = nameProvince; //省份
			this.addressInfo.city = nameCity; //城市
			this.addressInfo.county = nameCounty; //区县

			let province = this.areaList.find(item => item.pid == 0 && item.label == nameProvince);
			if (!province) return;

			let city = this.areaList.find(item => item.pid == province.id && item.label == nameCity);
			if (!city) return;

			let county = this.areaList.find(item => item.pid == city.id && item.label == nameCounty);
			if (!county) return;

			this.addressInfo.areaCode = county.id;
			this.addressInfo.postalCode = county.id; //暂且二者一致吧
		},
		
		showAreaPicker() {
			this.showPicker = true;
		},

		//处理保存地址
		onSave() {
			//准备参数
			let params = {
				id: this.addressInfo.id,
				name: this.addressInfo.name,
				tel: this.addressInfo.tel,
				province: this.addressInfo.province,
				city: this.addressInfo.city,
				county: this.addressInfo.county,
				area_code: this.addressInfo.areaCode, //
				postal_code: this.addressInfo.postalCode, //
				address_detail: this.addressInfo.addressDetail, //
				is_default: this.addressInfo.isDefault == true ? 1 : 0 //
			};

			AddressAPI.saveAddress(params).then(result => {
				uni.$u.toast(result.msg);
				//页面跳转
				setTimeout(() => {
					uni.navigateBack({
						delta: 1 //	url:'/pages/address/AddressList'
					});
				}, 1000);
			});
		},
		// 处理删除地址
		onDelete() {
			uni.showModal({
				title: '提示',
				content: '确认是要删除了吗？',
				success: result => {
					if (result.confirm) {
						AddressAPI.deleteAddressById(this.id).then(() => {
							uni.navigateBack({
								delta: 1 //	url:'/pages/address/AddressList'
							});
						});
					}
				}
			});
		}
	}
};
</script>

<style lang="scss" scoped>
.page-container {
	padding: 15px 15px 15px 15px;
	.top {
		padding: 22rpx;
		.item {
			display: flex;
			font-size: 32rpx;
			line-height: 100rpx;
			align-items: center;
			border-bottom: solid 2rpx $u-border-color;
			.left {
				width: 180rpx;
			}
			input {
				text-align: left;
			}
		}
	}
	.bottom {
		margin-top: 50rpx;
		padding: 40rpx;			
		line-height: 64rpx;
		display: flex;
		justify-content: space-between;
		border-bottom: solid 2rpx $u-border-color;		
		.left {			
			.set{
				font-size: 28rpx;	
			}
			.tips {
				font-size: 24rpx;
			}
		}
		.right {
		}	
	}
}
</style>
